import 'package:flutter/material.dart';
import 'package:flutter_archer/data/entity/models.dart';
import 'package:flutter_archer/data/repository/user_repository.dart';
import 'package:flutter_archer/shared/services/network/http_response.dart';
import 'package:flutter_archer/shared/shared.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';

class AuthController extends GetxController {
  final UserRepository userRepository;
  AuthController({required this.userRepository});

  final GlobalKey<FormState> registerFormKey = GlobalKey<FormState>();
  final registerEmailController = TextEditingController();
  final registerPasswordController = TextEditingController();
  final registerConfirmPasswordController = TextEditingController();
  bool registerTermsChecked = false;

  final GlobalKey<FormState> loginFormKey = GlobalKey<FormState>();
  final loginEmailController = TextEditingController();
  final loginPasswordController = TextEditingController();

  @override
  void onInit() {
    super.onInit();
  }

  @override
  void onReady() {
    super.onReady();
  }

  void register(BuildContext context) async {
    AppFocus.unfocus(context);
    if (registerFormKey.currentState!.validate()) {
      if (!registerTermsChecked) {
        CommonWidget.toast('Please check the terms first.');
        return;
      }
      HttpResponse rsp = await userRepository.register(
        RegisterRequest(
          email: registerEmailController.text,
          password: registerPasswordController.text,
        ),
      );
      if(rsp.ok){
        userRepository.saveToken(rsp.data.token);
      }else{
        CommonWidget.toast(rsp.error!.message);
      }
    }
  }

  void login(BuildContext context) async {
    AppFocus.unfocus(context);
    if (loginFormKey.currentState!.validate()) {
      EasyLoading.show(status: "登录中...",dismissOnTap: true);
      HttpResponse rsp = await userRepository.login(
        LoginRequest(
          username: loginEmailController.text,
          password: loginPasswordController.text,
        ),
      );
      EasyLoading.dismiss();
      if(rsp.ok){
        userRepository.saveToken(rsp.data.token);
      }else{
        CommonWidget.toast(rsp.error!.message);
      }
    }
  }

  void getUserInfo(BuildContext context) async {
    AppFocus.unfocus(context);
    EasyLoading.show(status: "加载中...",dismissOnTap: true);
    HttpResponse rsp = await userRepository.getUserInfo(
    );
    EasyLoading.dismiss();
    if(rsp.ok){
      CommonWidget.toast(rsp.data.toString());
    }else{
      CommonWidget.toast(rsp.error!.message);
    }
  }

  @override
  void onClose() {
    super.onClose();

    registerEmailController.dispose();
    registerPasswordController.dispose();
    registerConfirmPasswordController.dispose();

    loginEmailController.dispose();
    loginPasswordController.dispose();
  }
}
